package study.utils;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * SCALL码转换
 *
 * @Author 刘伟涛
 * @Date 2024/8/29 11:40
 **/
public class ASCIITranslateUtils {

    /**
     * 将ASCII码转成十六进制
     * @param input ASCII码
     * @return 十六进制
     */
    public static String asciiToHex(String input) {

        // 将字符串转换为 SCALL 码 (ASCII 码)
//        input = input + "\r\u0003";
        StringBuilder hexBuilder = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            // 是汉字,转
            if(c >= '\u4E00' && c <= '\u9FFF'){
                String stringToHex = stringToHex(Character.toString(c));
                hexBuilder.append(stringToHex);

            }else {
                hexBuilder.append(String.format("%02X", (int)c));// 将每个 SCALL 码转为两位十六进制
            }

        }
        String hexString = hexBuilder.toString();
        // 输出结果
        System.out.println("输入字符串: " + input);
        System.out.println("十六进制: " + hexString);
        return hexString;
    }

    /**
     * 十六进制转ASCII码
     * @param hexStr 十六进制
     * @return ASCII码
     */
    public static String hexToAscii(String hexStr){
        StringBuilder output = new StringBuilder("");

        // 去除所有的连字符
        hexStr = hexStr.replaceAll("[-:]", "").trim();
        for (int i = 0; i < hexStr.length(); i += 2) {
            // 获取两个字符作为一个字节
            String str = hexStr.substring(i, i + 2);
            // 将十六进制字节转换为整数，然后转换为对应的ASCII字符
            int intValue = Integer.parseInt(str, 16);

            switch (intValue) {
                case 0x02:
                    output.append("[STX]"); // 显示 "Start of Text"
                    break;
                case 0x03:
                    output.append("[ETX]"); // 显示 "End of Text"
                    break;
                case 0x0D:
                    output.append("[CR]");  // 显示 "Carriage Return"
                    break;
                case 0x0A:
                    output.append("[LF]");  // 显示 "Line Feed"
                    break;
                case 0x04:
                    output.append("[ETO]");  // 显示 "Line Feed"
                    break;
                default:
                    if (intValue >= 32 && intValue <= 126) {
                        // 如果是可见字符，则直接转换
                        char ch = (char) intValue;
                        output.append(ch);
                    } else {
                        // 处理其他不可见字符
                        output.append(String.format("[0x%02X]", intValue));
                    }
                    break;
            }
        }
        String asciiStr = output.toString();
        System.out.println("转换后的ASCII字符串: " + asciiStr);
        return asciiStr;
    }

    /**
     * 汉字转GB2312再转十六进制
     * @param input 汉字
     * @return 十六进制
     */
    public static String stringToHex(String input){
        try {
            // 将字符串转换为 GB2312 编码的字节数组
            byte[] gb2312Bytes = input.getBytes("GB2312");
            StringBuilder hexBuilder = new StringBuilder();
            for (byte b : gb2312Bytes) {
                hexBuilder.append(String.format("%02X", b)); // 将每个字节转为两位十六进制
            }
            String string = hexBuilder.toString();
            System.out.println("GB2312 编码的十六进制表示: " + string);
            return string;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 十六进制转汉字
     * @param gb2312Hex 十六进制
     * @return 汉字
     */
    public static String hexToString(String gb2312Hex) {

        // 将十六进制字符串转换为字节数组
        byte[] gb2312Bytes = hexStringToBytes(gb2312Hex);

        try {
            // 将 GB2312 编码的字节数组转换回字符串
            String decodedStringGB2312 = new String(gb2312Bytes, "GB2312");
            System.out.println("GB2312 解码后的字符串: " + decodedStringGB2312);
            return decodedStringGB2312;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 将十六进制字符串转换为字节数组
    public static byte[] hexStringToBytes(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i+1), 16));
        }
        return data;
    }


    // 将字符串转换为 ASCII 码 (ASCII 码)
    public static int[] convertStringToAscii(String input) {
        int[] scallCodes = new int[input.length()];
        for (int i = 0; i < input.length(); i++) {
            scallCodes[i] = input.charAt(i);
        }
        return scallCodes;
    }

    // 将 ASCII 码转换为十六进制表示
    public static String convertAsciiToHex(int[] scallCodes) {
        StringBuilder hexBuilder = new StringBuilder();
        for (int code : scallCodes) {
            hexBuilder.append(String.format("%02X", code)); // 将每个 SCALL 码转为两位十六进制
        }
        return hexBuilder.toString();
    }

    // 将数组转换为字符串形式显示
    public static String arrayToString(int[] array) {
        StringBuilder builder = new StringBuilder();
        for (int i : array) {
            builder.append(i).append(" ");
        }
        return builder.toString().trim();

    }

    /**
     * URL编码转UTF
     * @param encodedString URL编码
     * @return UTF
     * @throws UnsupportedEncodingException
     */
    public static String urlCodeToString(String encodedString) throws UnsupportedEncodingException {
        String resutl = null;
        if(!ObjectUtils.isEmpty(encodedString)){
            resutl = URLDecoder.decode(encodedString, "UTF-8");
            System.out.println("解码后的内容："+ resutl);
        }
        return resutl;
    }

    /**
     * UTF转URL编码
     * @param encodedString UTF
     * @return URL编码
     * @throws UnsupportedEncodingException
     */
    public static String stringToUrlCode(String encodedString) throws UnsupportedEncodingException {
        String resutl = null;
        if(!ObjectUtils.isEmpty(encodedString)){
            resutl = URLEncoder.encode(encodedString, "UTF-8");
            System.out.println("转码后的内容："+ resutl);
        }
        return resutl;
    }

    public static String findChineseCharacters(String hexString) {
        byte[] bytes = hexStringToBytes(hexString);
        String chineseCharacter = null;

        for (int i = 0; i < bytes.length - 1; i++) {
            int firstByte = bytes[i] & 0xFF;
            int secondByte = bytes[i + 1] & 0xFF;

            // 检查是否符合 GB2312/GBK 的汉字范围
            if (firstByte >= 0xB0 && firstByte <= 0xF7 && secondByte >= 0xA1 && secondByte <= 0xFE) {
                try {
                    chineseCharacter = new String(new byte[]{(byte) firstByte, (byte) secondByte}, "GB2312");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                i++; // 跳过下一个字节，因为已经处理过
            }
        }
        return chineseCharacter;
    }

}
